// 存所有任务数据，提供 “增删改查” 方法，让各页面数据同步
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { Task } from '../types/task';

function generateUniqueId() {
  const timestamp = Date.now().toString(36);
  const randomStr = Math.random().toString(36).substr(2, 5);
  return `${timestamp}${randomStr}`;
}

// 从本地存储获取任务，并添加异常处理，可以一直保存之前的内容
function getTasksFromLocalStorage(): Task[] {
  try {
    const tasksJson = localStorage.getItem('tasks');
    return tasksJson ? JSON.parse(tasksJson) : [];
  } catch (error) {
    console.error('Error getting tasks from local storage:', error);
    return [];
  }
}

// 保存任务到本地存储，并添加异常处理
function saveTasksToLocalStorage(tasks: Task[]) {
  try {
    localStorage.setItem('tasks', JSON.stringify(tasks));
  } catch (error) {
    console.error('Error saving tasks to local storage:', error);
  }
}

export const useTaskStore = defineStore('task', () => {
  // 使用ref定义响应式任务数组
  const tasks = ref<Task[]>(getTasksFromLocalStorage());

  // 待办任务计算属性（自动响应tasks变化）
  const pendingTasks = computed(() => 
    tasks.value.filter(task => !task.completed)
  );

  // 已完成任务计算属性（自动响应tasks变化）
  const completedTasks = computed(() => 
    tasks.value.filter(task => task.completed)
  );

  // 添加任务
  function addTask(task: Omit<Task, 'id' | 'completed'>) {
    const newTask: Task = {
      ...task,
      id: generateUniqueId(),
      completed: false
    };
    tasks.value.push(newTask);
    saveTasksToLocalStorage(tasks.value);
  }

  // 切换任务状态（核心修复点：确保正确更新并保存）
  function toggleTaskStatus(id: string) {
    const task = tasks.value.find(task => task.id === id);
    if (task) {
      task.completed = !task.completed;
      saveTasksToLocalStorage(tasks.value);
      // 移除手动触发响应式更新，让Vue自动处理
    }
  }

  // 删除任务
  function deleteTask(id: string) {
    tasks.value = tasks.value.filter(task => task.id !== id);
    saveTasksToLocalStorage(tasks.value);
  }

  return {
    tasks,
    pendingTasks,
    completedTasks,
    addTask,
    toggleTaskStatus,
    deleteTask
  };
});